<template>
  <div class="box">
    <!-- 头部搜索模块 -->
    <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :buttonList="buttonList" />
    <!-- 中间表格模块 -->
    <BaseTable :data="saleOrderData" :columns="saleOrderDataColumns" @details="selectDataList" :tableHeight="tableHeight"
      :pagination="false" :loading="loading"></BaseTable>

    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="queryAll.totalNum"></el-pagination>
    </div>
    <!-- 抽屉-->
    <el-drawer :before-close="handleClose" :title="title" :visible.sync="drawerInner" size="70%">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">
            <div>销售订单信息</div>
          </template>
          <el-form :model="rateForm" size="small" :rules="formRule" ref="formRef" style="padding:20px 10px;"
            label-position="top" label-width="100px" :disabled="showDisabled">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item>
                  <el-checkbox v-model="checked" :disabled="title == '开单' ? false : true">代收代付</el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="8">
                <el-form-item label="关联采购订单编号" prop="orderNo">
                  <el-input v-model="rateForm.orderNo" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="销售组织" prop="companyId">
                  <el-select clearable v-model="rateForm.companyId" placeholder="销售组织" style="width: 100%"
                    v-selecttext="rateForm.companyName, CompList, 'companyId'">
                    <el-option v-for="item in CompList" :key="item.companyId" :label="item.companyName"
                      :value="item.companyId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户名称" prop="customerCode">
                  <el-select clearable v-model="rateForm.customerCode" placeholder="客户名称" style="width: 100%"
                    v-selecttext="rateForm.customerName, customerList, 'customerId', 'customerName'">
                    <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerName"
                      :value="item.customerId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单编号" prop="orderNo">
                  <el-input v-model="rateForm.orderNo" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="作业部门" prop="deptId">
                  <el-select clearable v-model="rateForm.deptId" placeholder="作业部门" style="width: 100%"
                    v-selecttext="rateForm.deptName, workSectionList, 'deptId'">
                    <el-option v-for="item in workSectionList" :key="item.deptId" :label="item.deptName"
                      :value="item.deptId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="订单类型">
                  <el-select clearable v-model="rateForm.orderTypeCode" placeholder="订单类型" style="width: 100%"
                    v-selecttext="rateForm.orderTypeName, orderTypeList, 'dictValue', 'dictLabel'">
                    <el-option v-for="item in orderTypeList" :key="item.dictValue" :label="item.dictLabel"
                      :value="item.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单据日期" prop="orderDate">
                  <el-date-picker v-model="rateForm.orderDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="船名航次" prop="shipvoyageId">
                  <el-select clearable v-model="rateForm.shipvoyageId" placeholder="客户名称" style="width: 100%"
                    v-selecttext="rateForm.shipvoyageName, shipVoyageData, 'shipvoyageId'" @change="shipvoyageChange">
                    <el-option v-for="item in shipVoyageData" :key="item.shipvoyageId" :label="item.shipvoyageName"
                      :value="item.shipvoyageId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="船舶交接量" prop="handoverVolume">
                  <el-input v-model="rateForm.handoverVolume" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="作业内容" prop="rateTypeCode">
                  <el-select clearable v-model="rateForm.rateTypeCode" placeholder="作业内容" style="width: 100%"
                    v-selecttext="rateForm.rateTypeName, rateTypeList, 'dictValue', 'dictLabel'"
                    @change="changeRateItemData">
                    <el-option v-for="item in rateTypeList" :key="item.dictValue" :label="item.dictLabel"
                      :value="item.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="货种名称" prop="cargoCategoryName">
                  <el-input v-model="rateForm.cargoCategoryName" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="贸别" prop="tradeType">
                  <el-input v-model="rateForm.tradeType" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请机械" prop="equipment">
                  <el-input v-model="rateForm.equipment"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="16">
                <el-form-item label="备注" prop="remark">
                  <el-input size="small" maxlength="500" type="textarea" :autosize="{ minRows: 2, maxRows: 3 }"
                    placeholder="请输入备注且最多500个字" v-model="rateForm.remark" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            <div>计费相关信息</div>
            <div v-if="title == '详情' ? false : true" style="position: relative; left: 85%;" @click.stop="addLotting">
              <el-link type="primary">添加</el-link>
            </div>
          </template>
          <el-form :model="rateForm" ref="basisRulesRef" size="small" :disabled="form1">
            <el-table :data="rateForm.list" style="width: 100%" border height="200px">
              <el-table-column label="作业类型">
                <template slot-scope="scope">
                  <el-form-item :prop="`list[${scope.$index}].rateItemCode`"
                    :rules="[{ required: true, message: '作业类型不能为空' }]">
                    <el-select v-model="scope.row.rateItemCode"
                      @change="changeValue('rateItemCode', scope.$index, scope.row.rateItemCode)">
                      <el-option v-for="item in rateTypeZiList" :key="item.rateItemCode" :label="item.rateItemName"
                        :value="item.rateItemCode"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="车号">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `list[${scope.$index}].carNo` : ''">
                    <el-input v-model="scope.row.carNo"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="起点区域">
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select clearable v-model="scope.row.startRegionCode"
                      @change="changeValue('startRegionCode', scope.$index, scope.row.startRegionCode)">
                      <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="终点区域">
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select clearable v-model="scope.row.endRegionCode"
                      @change="changeValue('endRegionCode', scope.$index, scope.row.endRegionCode)">
                      <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="作业量" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="`list[${scope.$index}].workload`"
                    :rules="[{ required: true, message: '作业量不能为空' }]">
                    <el-input v-model.number="scope.row.workload"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `list[${scope.$index}].unitCode` : ''"
                    :rules="[{ required: true, message: '单位不能为空' }]">
                    <el-select v-model="scope.row.unitCode"
                      @change="changeValue('unitCode', scope.$index, scope.row.unitCode)">
                      <el-option v-for="item in unitCodeList" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单价" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `list[${scope.$index}].rate` : ''"
                    :rules="[{ required: true, message: '单价不能为空' }]">
                    <el-input v-model="scope.row.rate"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额" width="100">
                <template slot-scope="scope">
                  <el-form-item>
                    <el-input v-model="scope.row.amount"
                      onkeyup="value=value.replace(^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$, '')"
                      :disabled="title == '结算' ? false : true"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="税率" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `list[${scope.$index}].tax` : ''"
                    :rules="[{ required: true, message: '税率不能为空' }]">
                    <el-input v-model="scope.row.tax"
                      onkeyup="value=value.replace(^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$, '')"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="税额" width="100" prop="taxAmount">
              </el-table-column>
              <el-table-column v-if="title == '详情' ? false : true" label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-collapse-item>
        <el-collapse-item name="3" v-if="checked">
          <template slot="title">
            <div>采购订单信息</div>
            <div v-if="title == '详情' ? false : true" @click.stop="addListItem" style="position: relative; left: 85%;">
              <el-link type="primary">添加</el-link>
            </div>
            <div style="margin: 0 auto">
              <span>供货商：</span>
              <el-select clearable v-model="rateForm.ghsCode" placeholder="客户名称" size="small"
                v-selecttext="rateForm.ghsName, customerList, 'customerId', 'customerName'">
                <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerName"
                  :value="item.customerId"></el-option>
              </el-select>
            </div>
          </template>
          <el-form :model="rateForm" ref="formRef1" size="small" :disabled="form2">
            <el-table :data="rateForm.listItem" style="width: 100%" border height="200px">
              <el-table-column label="作业类型">
                <template slot-scope="scope">
                  <el-form-item :prop="`listItem[${scope.$index}].rateItemCode`"
                    :rules="[{ required: true, message: '作业类型不能为空' }]">
                    <el-select v-model="scope.row.rateItemCode"
                      @change="changeValue('rateItemCode1', scope.$index, scope.row.rateItemCode)">
                      <el-option v-for="item in rateTypeZiList" :key="item.rateItemCode" :label="item.rateItemName"
                        :value="item.rateItemCode"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="车号">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `listItem[${scope.$index}].carNo` : ''">
                    <el-input v-model="scope.row.carNo"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="起点区域">
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select clearable v-model="scope.row.startRegionCode"
                      @change="changeValue('startRegionCode1', scope.$index, scope.row.startRegionCode)">
                      <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="终点区域">
                <template slot-scope="scope">
                  <el-form-item>
                    <el-select clearable v-model="scope.row.endRegionCode"
                      @change="changeValue('endRegionCode1', scope.$index, scope.row.endRegionCode)">
                      <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="作业量" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="`listItem[${scope.$index}].workload`"
                    :rules="[{ required: true, message: '作业量不能为空' }]">
                    <el-input v-model.number="scope.row.workload"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单位" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `listItem[${scope.$index}].unitCode` : ''"
                    :rules="[{ required: true, message: '单位不能为空' }]">
                    <el-select v-model="scope.row.unitCode"
                      @change="changeValue('unitCode1', scope.$index, scope.row.unitCode)">
                      <el-option v-for="item in unitCodeList" :key="item.dictValue" :label="item.dictLabel"
                        :value="item.dictValue"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单价" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `listItem[${scope.$index}].rate` : ''"
                    :rules="[{ required: true, message: '单价不能为空' }]">
                    <el-input v-model="scope.row.rate"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额" width="100">
                <template slot-scope="scope">
                  <el-form-item>
                    <el-input v-model="scope.row.amount"
                      onkeyup="value=value.replace(^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$, '')"
                      :disabled="title == '结算' ? false : true"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="税率" width="100">
                <template slot-scope="scope">
                  <el-form-item :prop="title == '结算' ? `listItem[${scope.$index}].tax` : ''"
                    :rules="[{ required: true, message: '税率不能为空' }]">
                    <el-input v-model="scope.row.tax"
                      onkeyup="value=value.replace(^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$, '')"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="税额" width="100" prop="taxAmount">
              </el-table-column>
              <el-table-column v-if="title == '详情' ? false : true" label="操作" width="80" fixed="right">
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleDelete2(scope.$index, scope.row)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      <div class="demo-drawer__footer">
        <el-button type="primary" v-if="title == '详情' ? false : true" @click="submitInner()" :loading="ineerLoading"
          size="small">
          {{ ineerLoading ? "提交中 ..." : title }}
        </el-button>
        <el-button size="small" @click="drawerInner = false">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTableCheck from '@/components/BaseTable/baseTablecheck'
import BaseTable from '@/components/BaseTable'
import api from '@/api/Business/saleOrder/index'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
export default {
  components: {
    BaseTable,
    headerSearch,
    BaseTableCheck
  },
  data() {
    return {
      menuFlag: false,
      oldOut: {},
      oldInner: {},
      ineerLoading: false,
      tableHeight: window.innerHeight - 200,
      // 搜索框显示对象
      selectObject: [
        {
          name: '销售组织',
          type: 'select',
          modelName: 'companyName',
          selectLabel: 'companyName',
          selectValue: 'companyName',
          selectData: []
        }, {
          name: '客户名称',
          type: 'select',
          modelName: 'customerName',
          selectLabel: 'customerName',
          selectValue: 'customerName',
          selectData: []
        }
      ],
      // 按钮的list
      buttonList: [
        { label: '开单', disabled: false, icon: 'el-icon-edit-outline', type: 'primary', click: () => this.addDrawerForm, permission: 'businessDataSubsystem:order:Insert' },
        { label: '完工', disabled: false, icon: 'el-icon-circle-check', type: 'primary', click: () => this.nextDrawerForm, permission: 'businessDataSubsystem:order:updateItem' },
        { label: '结算', disabled: false, icon: 'el-icon-tickets', type: 'primary', click: () => this.overDrawerForm, permission: 'businessDataSubsystem:order:updateOrder' },
        { label: '撤销', disabled: false, icon: 'el-icon-refresh-right', type: 'primary', click: () => this.cancelDrawerForm, permission: 'businessDataSubsystem:order:updateStatus' },
        { label: '复制', disabled: false, icon: 'el-icon-document-copy', type: 'primary', click: () => this.copyDrawerForm, permission: 'businessDataSubsystem:order:Update' }
      ],
      saleOrderDataColumns: [ // table表头
        { prop: 'companyName', label: '销售组织', isShort: true },
        { prop: 'customerName', label: '客户名称', isShort: true },
        {
          prop: 'orderNo',
          label: '订单编号',
          render: (h, params) => {
            return h(
              'div',
              [
                h('span', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML:
                      `<span style='color:#0B6CD6;cursor:pointer'><span  style='padding-left:5px;'>${params.row.orderNo}</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleEditOut(params.row)
                    }
                  }
                })
              ]
            )
          }
        },
        { prop: 'orderDate', label: '单据日期' },
        { prop: 'workloads', label: '总数量' },
        { prop: 'amounts', label: '总金额' },
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'tradeType', label: '贸别' },
        {
          prop: 'status',
          label: '状态',
          render(h, params) {
            if (params.row.status == '1') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'warning'
                },
                domProps: {
                  innerHTML: '开单'
                }
              })
            } else if (params.row.status == '2') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'success'
                },
                domProps: {
                  innerHTML: '完工'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini'
              },
              domProps: {
                innerHTML: '结算'
              }
            })
          }
        },
        { prop: 'createName', label: '创建人', isShort: true },
        { prop: 'createTime', label: '创建时间' },
        {
          label: '操作',
          width: 200,
          fixed: 'right',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              {
                calss: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.status != '1'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleEdit(params.$index, params.row)
                    }
                  }
                }),

                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.status != '1'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#F75E5E;'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.deleteCargoInfo('1', params.row.id)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      checked: false,
      activeNames: ['1', '2', '3'],
      saleOrderData: [],
      storeHouseList: [],
      locationList: [],
      shipVoyageData: [],
      CompList: [],
      customerList: [],
      workSectionList: [],
      orderTypeList: [],
      rateTypeList: [],
      rateTypeZiList: [],
      cargoCategoryData: [],
      regionList: [],
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        totalNum: 0
      },
      title: '',
      detailsData: {},
      drawerInner: false,
      showDisabled: false,
      form1: false,
      form2: false,
      rateForm: {
        ghsCode: '',
        ghsName: '',
        tradeType: '',
        rateTypeCode: '',
        rateTypeName: '',
        cargoCategoryName: '',
        cargoCategoryCode: '',
        handoverVolume: '',
        shipName: '',
        voyage: '',
        status: '',
        list: [],
        listItem: [],
        orderDate: new Date()
      },
      formRule: {
        companyId: [
          { required: true, message: '销售组织不能为空' }
        ],
        customerCode: [
          { required: true, message: '客户名称不能为空' }
        ],
        orderTypeCode: [
          { required: true, message: '订单类型不能为空' }
        ],
        orderDate: [
          { required: true, message: '单据日期不能为空' }
        ],
        rateTypeCode: [
          { required: true, message: '工作内容不能为空' }
        ]
      }
    }
  },
  async activated() {
    this.getListComp()
    this.getShipvoyage()
    this.getCustomer()
    this.getworksection()
    this.getDictData()
    // this.getCargoCategory()
  },
  methods: {
    // 获取组织
    getListComp() {
      publicapi.getListComp().then(res => {
        this.CompList = res.data.data
        this.selectObject[0].selectData = this.CompList
      })
    },
    // 获取客户
    getCustomer() {
      publicapi.getlistCustomer().then(res => {
        this.customerList = res.data.data
        this.selectObject[1].selectData = this.customerList
      })
    },
    // 获取部门(作业工段)
    getworksection() {
      publicapi.getworksection().then(res => {
        this.workSectionList = res.data.data
      })
    },
    // 获取字典数据
    getDictData() {
      // 订单类型
      publicapi.getDictData('ORDER_TYPE').then(res => {
        this.orderTypeList = res.data.data.ORDER_TYPE
      })
      // 作业内容
      publicapi.getDictData('RATE_TYPE').then(res => {
        this.rateTypeList = res.data.data.RATE_TYPE
      })
      // 所属区域
      publicapi.getDictData('REGION').then(res => {
        this.regionList = res.data.data.REGION
      })
      // 单位
      publicapi.getDictData('BILLING_UNIT').then(res => {
        this.unitCodeList = res.data.data.BILLING_UNIT
      })
    },
    /**
 * 获取船名航次
 */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.shipVoyageData = res.data.data
    },
    /**
     * 获取货种
     */
    async getCargoCategory() {
      const res = await publicapi.getlistCargoCategory()
      this.cargoCategoryData = res.data.data
    },
    // 查询货主
    async getlistCustomer() {
      await publicapi.getlistCustomer().then(res => {
        if (res.data.code == '0000') {
          this.locationList = res.data.data
        }
      })
    },
    // 获取数据
    async getData() {
      this.loading = true
      await api.getData(this.queryAll).then(res => {
        if (res.status == '200') {
          this.saleOrderData = res.data.data.pages
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.loading = false
        }
      })
    },
    // 开单按钮
    async addDrawerForm() {
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.showDisabled = false
      this.form1 = false
      this.form2 = false
      this.title = '开单'
      this.rateForm = this.$options.data().rateForm
      this.rateTypeZiList = []
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate()
      })
    },
    // 完工按钮
    nextDrawerForm() {
      if (!this.detailsData.id) {
        return this.$message.warning('请选择一条数据')
      }
      this.getDataById()
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.title = '完工'
      this.showDisabled = true
      this.form1 = false
      this.form2 = false
    },
    // 结算按钮
    overDrawerForm() {
      if (!this.detailsData.id) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.showDisabled = true
      this.form1 = false
      this.form2 = false
      this.title = '结算'
      this.getDataById()
    },
    // 撤销按钮
    cancelDrawerForm() {
      if (this.detailsData.id) {
        this.$confirm('是否撤销？').then(() => {
          api.cancelData(this.detailsData.id).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('撤销成功')
              this.getData()
            }
          })
        })
      } else {
        return this.$message.warning('请选择一条数据')
      }
    },
    // 复制按钮
    copyDrawerForm() {
      if (Object.keys(this.detailsData).length == 0) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.showDisabled = false
      this.form1 = false
      this.form2 = false
      this.title = '复制'
      api.getSummaryById(this.detailsData.id).then(res => {
        if (res.status == '200') {
          const form = res.data.data
          delete form.id
          delete form.orderNo
          if (form.list.length > 0) {
            form.list.forEach(item => {
              item.id = ''
              item.orderId = ''
            })
          }
          this.rateForm = form
          this.getRateItem()
        }
      })
    },
    // 船名航次选择
    shipvoyageChange(val) {
      if (val) {
        publicapi.getDataById(val).then(res => {
          if (res.data.code == '0000') {
            const shipVoyageForm = res.data.data
            this.rateForm.tradeType = shipVoyageForm.tradeType
            this.rateForm.cargoCategoryName = shipVoyageForm.cargoCategoryName
            this.rateForm.cargoCategoryCode = shipVoyageForm.cargoCategoryCode
            this.rateForm.handoverVolume = shipVoyageForm.actualLoad
            this.rateForm.shipName = shipVoyageForm.shipName
            this.rateForm.voyage = shipVoyageForm.voyage
          }
        })
      } else {
        this.rateForm.tradeType = ''
        this.rateForm.cargoCategoryName = ''
        this.rateForm.cargoCategoryCode = ''
        this.rateForm.handoverVolume = ''
        this.rateForm.shipName = ''
        this.rateForm.voyage = ''
      }
    },
    // 选中数据
    selectDataList(val) {
      this.detailsData = {}
      this.detailsData = val
      if (this.detailsData.status == '1') {
        this.buttonList.filter(item => item.label == '结算')[0].disabled = false
        this.buttonList.filter(item => item.label == '完工')[0].disabled = false
        this.buttonList.filter(item => item.label == '撤销')[0].disabled = true
      } else if (this.detailsData.status == '2') {
        this.buttonList.filter(item => item.label == '完工')[0].disabled = false
        this.buttonList.filter(item => item.label == '结算')[0].disabled = false
        this.buttonList.filter(item => item.label == '撤销')[0].disabled = true
      } else if (this.detailsData.status == '3') {
        this.buttonList.filter(item => item.label == '完工')[0].disabled = true
        this.buttonList.filter(item => item.label == '结算')[0].disabled = true
        this.buttonList.filter(item => item.label == '撤销')[0].disabled = false
      }
    },
    // 编辑
    async handleEdit(index, row) {
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.showDisabled = false
      this.form1 = false
      this.form2 = false
      this.title = '编辑'
      await api.getSummaryById(row.id).then(res => {
        if (res.status == '200') {
          this.rateForm = res.data.data
          if (this.rateForm.ghsCode) {
            this.checked = true
          } else {
            this.checked = false
          }
          this.getRateItem()
        }
      })
    },
    // 根据id查询
    async getDataById() {
      await api.getSummaryById(this.detailsData.id).then(res => {
        if (res.status == '200') {
          this.rateForm = res.data.data
          if (!this.rateForm.listItem) {
            this.rateForm.listItem = []
          }
          if (this.rateForm.ghsCode) {
            this.checked = true
          } else {
            this.checked = false
          }
          this.getRateItem()
        }
      })
    },
    // 删除
    deleteCargoInfo(index, id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteById(id).then(res => {
          if (res.data.code == '0000') {
            this.$message.success('删除成功')
            this.getData()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改作业内容
    changeRateItemData() {
      if (this.rateForm.list.length > 0) {
        this.rateForm.list.forEach(item => {
          item.rateItemCode = ''
          item.rateItemName = ''
        })
      }
      if (this.rateForm.listItem) {
        this.rateForm.listItem.forEach(item => {
          item.rateItemCode = ''
          item.rateItemName = ''
        })
      }
      this.getRateItem()
    },
    // 获取作业类型
    async getRateItem() {
      if (this.rateForm.rateTypeCode) {
        this.rateTypeZiList = []
        await api.getRateItem(this.rateForm.rateTypeCode).then(res => {
          if (res.data.code == '0000') {
            this.rateTypeZiList = res.data.data
          }
        })
      }
    },
    /**
     * 新建、编辑保存
     */
    submitInner() {
      if (this.title == '结算' && this.rateForm.list.length == 0) {
        return this.$message.warning('计费数据不能为空')
      }
      if (this.checked) {
        if (!this.rateForm.ghsCode) {
          return this.$message.warning('供货商不能为空')
        }
      }
      switch (this.title) {
        case '完工':
          this.rateForm.status = '2'
          break;
        case '结算':
          this.rateForm.status = '3'
          break;
        case '开单':
          this.rateForm.status = '1'
          break;
        case '复制':
          this.rateForm.status = '1'
          break;
        default:
          break;
      }
      if (this.title == '复制') {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            api.addData(this.rateForm).then(res => {
              if (res.data.code == '0000') {
                this.$message.success('开单成功')
                this.drawerInner = false
                this.rateForm = {}
                this.getData()
              }
            })
          }
        })
      }
      const p1 = new Promise((resolve) => {
        this.$refs.basisRulesRef.validate((data) => {
          if (data) {
            resolve('成功')
          }
        })
      })

      const p2 = new Promise((resolve) => {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            resolve('成功')
          }
        })
      })
      if (this.rateForm.ghsCode) {
        var p3 = new Promise((resolve) => {
          this.$refs['formRef1'].validate((item) => {
            if (item) {
              resolve('成功')
            }
          })
        })
      }
      Promise.all([p1, p2, p3]).then(result => {
        if (this.title == '开单') {
          api.addData(this.rateForm).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('开单成功')
              this.drawerInner = false
              this.rateForm = {}
              this.getData()
            }
          })
        } else if (this.title == '编辑') {
          api.updateData(this.rateForm).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('保存成功')
              this.drawerInner = false
              this.rateForm = {}
              this.getData()
            }
          })
        } else if (this.title == '完工') {
          api.updateDataFinish(this.rateForm).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('保存成功')
              this.drawerInner = false
              this.rateForm = {}
              this.getData()
            }
          })
        } else if (this.title == '结算') {
          api.updateDataOrder(this.rateForm).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('保存成功')
              this.drawerInner = false
              this.rateForm = {}
              this.getData()
            }
          })
        }
      }).catch(err => {
      })
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.detailsData = {}
      this.getData()
    },
    // 添加明细信息
    addLotting() {
      const data = {
        orderId: this.detailsData.id,
        rateItemCode: '',
        rateItemName: '',
        carNo: '',
        startRegionCode: '',
        startRegionName: '',
        endRegionCode: '',
        endRegionName: '',
        workload: '',
        unitCode: '',
        unitName: '',
        rate: '',
        amount: '',
        tax: '',
        taxAmount: ''
      }
      this.rateForm.list.push(data)
    },
    // 添加明细信息
    addListItem() {
      const data = {
        orderId: this.detailsData.id,
        rateItemCode: '',
        rateItemName: '',
        carNo: '',
        startRegionCode: '',
        startRegionName: '',
        endRegionCode: '',
        endRegionName: '',
        workload: '',
        unitCode: '',
        unitName: '',
        rate: '',
        amount: '',
        tax: '',
        taxAmount: ''
      }
      this.rateForm.listItem.push(data)
    },
    // 点击查看详情
    async handleEditOut(row) {
      if (!this.drawerInner) {
        this.title = '详情'
        this.drawerInner = true
      }
      await api.getSummaryById(row.id).then(res => {
        if (res.status == '200') {
          this.rateForm = res.data.data
          if (this.rateForm.ghsCode) {
            this.checked = true
          } else {
            this.checked = false
          }
          this.showDisabled = true
          this.form1 = true
          this.form2 = true
        }
      })
    },
    // 下拉框数据
    changeValue(type, index, val) {
      if (type == 'rateItemCode') {
        this.rateForm.list[index].rateItemName = this.rateTypeZiList.filter(item => item.rateItemCode == val)[0].rateItemName
      } else if (type == 'startRegionCode') {
        this.rateForm.list[index].startRegionName = this.regionList.filter(item => item.dictValue == val)[0].dictLabel
      } else if (type == 'endRegionCode') {
        this.rateForm.list[index].endRegionName = this.regionList.filter(item => item.dictValue == val)[0].dictLabel
      } else if (type == 'unitCode') {
        this.rateForm.list[index].unitName = this.unitCodeList.filter(item => item.dictValue == val)[0].dictLabel
      } else if (type == 'rateItemCode1') {
        this.rateForm.listItem[index].rateItemName = this.rateTypeZiList.filter(item => item.rateItemCode == val)[0].rateItemName
      } else if (type == 'startRegionCode1') {
        this.rateForm.listItem[index].startRegionName = this.regionList.filter(item => item.dictValue == val)[0].dictLabel
      } else if (type == 'endRegionCode1') {
        this.rateForm.listItem[index].endRegionName = this.regionList.filter(item => item.dictValue == val)[0].dictLabel
      } else if (type == 'unitCode1') {
        this.rateForm.listItem[index].unitName = this.unitCodeList.filter(item => item.dictValue == val)[0].dictLabel
      }
    },
    handleDelete(index, rows) {
      this.rateForm.list.splice(index, 1);
      // if (rows.id) {
      //   api.deleteByIdZi(rows.id).then(res => {
      //     if (res.data.code == '0000') {
      //       this.$message.success('删除成功')
      //       this.getDataById()
      //     }
      //   })
      // } else {

      // }
    },
    handleDelete2(index, rows) {
      this.rateForm.listItem.splice(index, 1);
      // if (rows.id) {
      //   api.deleteByIdZi(rows.id).then(res => {
      //     if (res.data.code == '0000') {
      //       this.$message.success('删除成功')
      //       this.getDataById()
      //     }
      //   })
      // } else {

      // }
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getData()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerInner) {
        oldV = this.oldInner
        newV = this.innerForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../../assets/searchfrom.less";

.page {
  background: #ffffff;
  text-align: right;
  border-radius: 0 0 4px 4px;
  padding: 5px 20px;
}

/deep/.el-drawer__body {
  margin-bottom: 54px;
}

.el-table__cell>.cell>.el-form-item--small.el-form-item {
  margin-bottom: 0px;
}

/deep/.el-drawer__header {
  margin-bottom: 0;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}

/deep/ s.el-table__fixed-header-wrapper {
  z-index: 0 !important;
}
</style>
